package com.zzjson.client;

import com.zzjson.RpcRequest;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2020 shuncom team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description :网络传输</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2020年02月23日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class RpcNetTransport {
	private String host;
	private int port;

	public RpcNetTransport(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public Object send(RpcRequest request) {
		Socket socket = null;
		Object result = null;
		ObjectOutputStream outputStream = null;
		ObjectInputStream inputStream = null;

		try {
			socket = new Socket(host, port);
			outputStream = new ObjectOutputStream(socket.getOutputStream());
			outputStream.writeObject(request);
			outputStream.flush();

			inputStream = new ObjectInputStream(socket.getInputStream());
			return inputStream.readObject();
		} catch (IOException | ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}


		}
		return null;
	}
}
